package com.spica.platform.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * http 工具类
 */
public class HttpUtil {

	public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
    private static final String XML_HTTP_REQUEST = "XMLHttpRequest";
    private static final String X_REQUESTED_WITH = "X-Requested-With";
    private static final String CONTENT_TYPE_JSON = "application/json";
    /**
     * 获取 HttpServletRequest
     *
     * @return {HttpServletRequest}
     */
    public static HttpServletRequest getRequest() {
        return RequestContextHolder.getRequestAttributes() == null ? null
                : ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        return HttpUtil.post(requestUrl, accessToken, CONTENT_TYPE, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }

    /**
     * 通过query字符串得到参数的map
     * @param queryString ?后的字符
     * @return
     */
    public static Map<String, String> getQueryMap(String queryString){
        if(StringUtils.isNotBlank(queryString)){
            return Arrays.stream(queryString.split("&")).map(item -> item.split("="))
                    .collect(Collectors.toMap(key -> key[0], value -> value.length > 1 && StringUtils.isNotBlank(value[1]) ? value[1] : ""));
        }
        return Collections.emptyMap();
    }

    /**
     * 通过url获取参数map
     * @param uri
     * @return
     */
    public static Map<String, String> getQueryMap(URI uri){
        if(Objects.nonNull(uri)){
            return getQueryMap(uri.getQuery());
        }
        return Collections.emptyMap();
    }

    public static boolean isAjaxResponse(HttpServletRequest request) {
        return isAjaxRequest(request) || isContentTypeJson(request) || isPostRequest(request);
    }

    public static boolean isObjectRequest(HttpServletRequest request) {
        return isPostRequest(request) && isContentTypeJson(request);
    }

    public static boolean isObjectRequest(SavedRequest request) {
        return isPostRequest(request) && isContentTypeJson(request);
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        return XML_HTTP_REQUEST.equals(request.getHeader(X_REQUESTED_WITH));
    }

    public static boolean isAjaxRequest(SavedRequest request) {
        return request.getHeaderValues(X_REQUESTED_WITH).contains(XML_HTTP_REQUEST);
    }

    public static boolean isContentTypeJson(HttpServletRequest request) {
        return request.getHeader(HttpHeaders.CONTENT_TYPE).contains(CONTENT_TYPE_JSON);
    }

    public static boolean isContentTypeJson(SavedRequest request) {
        return request.getHeaderValues(HttpHeaders.CONTENT_TYPE).contains(CONTENT_TYPE_JSON);
    }

    public static boolean isPostRequest(HttpServletRequest request) {
        return HttpMethod.POST.name().equals(request.getMethod());
    }

    public static boolean isPostRequest(SavedRequest request) {
        return HttpMethod.POST.name().equals(request.getMethod());
    }
}
